import React, {useEffect, useState} from 'react';
import {useLocation, useNavigate} from 'react-router-dom';
import {useUserStore} from '@store/userStore.ts';
import Snackbar from '@mui/material/Snackbar';
import Alert from '@mui/material/Alert';
import {getToken, getUserFromToken, parseToken, removeToken} from "./auth.ts";

interface PermissionGuardProps {
    children: React.ReactNode;
    requireAuth?: boolean;
}

const PermissionGuard: React.FC<PermissionGuardProps> = ({children, requireAuth = false}) => {
    const user = useUserStore((state) => state.user);
    const setUser = useUserStore((state) => state.setUser);
    const clearUser = useUserStore((state) => state.clearUser);
    const location = useLocation();
    const navigate = useNavigate();
    const [open, setOpen] = useState(false);

    // 1. /logout 路由处理
    useEffect(() => {
        if (location.pathname === '/logout') {
            clearUser();
            removeToken();
            navigate('/login', {replace: true});
        }
        // eslint-disable-next-line
    }, [location.pathname]);

    // 2. /login 路由处理（假设登录页面已处理token保存，这里兜底解析）
    useEffect(() => {
        if (location.pathname === '/login') {
            const token = getToken();
            if (token) {
                const userInfo = parseToken(token);
                if (userInfo) setUser(userInfo);
            }
        }
        // eslint-disable-next-line
    }, [location.pathname]);

    // 3. 访问需要权限页面时
    useEffect(() => {
        if (requireAuth) {
            if (!user) {
                // 先查 token
                const userInfo = getUserFromToken();
                if (userInfo) {
                    setUser(userInfo);
                    return;

                }
                // token 也没有，弹窗提示
                setOpen(true);
            }
        }
        // eslint-disable-next-line
    }, [requireAuth, user, setUser, location.pathname]);

    // 用户点击提示后跳转
    const handleClose = () => {
        setOpen(false);
        navigate('/login', {replace: true});
    };

    if (requireAuth && !user) {
        // 只弹窗，不直接跳转
        return (
            <>
                <Snackbar open={open} autoHideDuration={null} onClose={handleClose}>
                    <Alert severity="warning" sx={{width: '100%'}} onClose={handleClose}>
                        请先登录
                    </Alert>
                </Snackbar>
            </>
        );
    }

    return <>{children}</>;
};

export default PermissionGuard;
